/*
 * Copyright (C) 2007-2008 SlideMe client
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.slideme.android.manager.download;

import org.slideme.android.manager.UnsupportedContentHandlerException;
import org.slideme.android.manager.media.Media;
import org.slideme.android.manager.media.MediaMarshaller;
import org.slideme.android.manager.media.MediaObject;
import org.slideme.android.manager.media.Product;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * Provides services for downloading of content.
 */
public interface DownloadUserAgent {

    void init(DownloadContext downloadContext);

    /**
     * Downloads the specified mediaDescriptor or content
     *
     * @param mediaDescriptorURI the mediaDescriptor or content to download
     * @throws IOException if there is a problem in downloading content
     */
    void downloadContent(URI mediaDescriptorURI) throws IOException;

    public static class Factory {
        /**
         * Constructor
         */
        private Factory() {
        }

        /**
         * Returns a default instance of the download user agent
         *
         * @return a default instance of the download user agent
         */
        public static DownloadUserAgent createDefaultDownloadUserAgent(final String mimeType) {
            return new DownloadUserAgent() {

                private DownloadContext downloadContext;

                public void init(DownloadContext downloadContext) {
                    if (downloadContext == null) {
                        throw new IllegalArgumentException("downloadContext");
                    }
                    this.downloadContext = downloadContext;
                }

                public void downloadContent(URI mediaDescriptorURI) throws IOException {
                    if (mediaDescriptorURI == null) {
                        throw new IllegalArgumentException("mediaDescriptorURI");
                    }

                    URL url = mediaDescriptorURI.toURL();
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    Media media = MediaMarshaller.marshal(connection.getInputStream());

                    //  contentHandler.download(server, new FileOutputStream("/server/app/"
                    //          + mediaObject.getMeta().getName()));

                    for (Product product : media.getProduct()) {
                        for (MediaObject mediaObject : product.getMediaObject()) {
                            for (URI server : mediaObject.getObjectURI().getServer()) {
                                URI serverUri;
                                try {
                                    serverUri = new URI(server.toString().replaceAll("&amp;", "&"));
                                } catch (URISyntaxException e) {
                                    throw new IOException(e.getMessage());
                                }
                                org.slideme.android.manager.ContentHandler contentHandler;
                                try {
                                    contentHandler = downloadContext.getContentHandlerFor(mimeType);
                                } catch (UnsupportedContentHandlerException e) {
                                    throw new IOException(e.getMessage());
                                }
                                try {
                                    contentHandler.download(serverUri, mediaObject.getMeta().getName(),
                                            downloadContext.getContext().getPackageManager());
                                } catch (IOException e) {
                                    continue;
                                }
                                //find handler based on mime-type and install
                            }
                        }
                    }
                }
            };
        }
    }
}
